package edu.biwu.response;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;

@WebServlet("/resp/download01")
public class RespDownload01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取互联网传递过来的参数
        String fileName = request.getParameter("fileName");

        //2.设置MIME和下载响应头 Content-Disposition: attachment;filename=文件名
        String mimeType = getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment;filename = " + fileName);

        //3.将指定的文件的字节写给浏览器
        BufferedInputStream bis = new BufferedInputStream(getServletContext().getResourceAsStream("/download/" + fileName));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

        int b;
        while ((b = bis.read()) != -1) {
            //写给浏览器
            bos.write(b);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
